using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Ewe_Files;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Ewe_Files
{
    /// <summary>
    /// 母羊档案更新命令处理器
    /// </summary>
    public class UpdateEweFileCommandHandler : IRequestHandler<UpdateEweFileCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<EweFile> _eweRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateEweFileCommandHandler> _logger;

        public UpdateEweFileCommandHandler(
            IBaseRepository<EweFile> eweRepository,
            IMapper mapper,
            ILogger<UpdateEweFileCommandHandler> logger)
        {
            _eweRepository = eweRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理母羊档案更新命令
        /// </summary>
        /// <param name="request">母羊档案更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateEweFileCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("母羊档案更新请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"母羊档案更新数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询母羊档案
                var eweFile = await _eweRepository.GetByIdAsync(request.EweId);
                
                if (eweFile == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.EweId} 的母羊档案");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的母羊档案", data = false };
                }

                // 检查是否已被删除
                if (eweFile.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.EweId} 的母羊档案已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "母羊档案已被删除", data = false };
                }

                // 更新实体
                eweFile.EarSignal = request.EarSignal;
                eweFile.Variety = request.Variety;
                eweFile.ElectronicEarTag = request.ElectronicEarTag;
                eweFile.GeneRank = request.GeneRank;
                eweFile.FatherNumber = request.FatherNumber;
                eweFile.MotherNumber = request.MotherNumber;
                eweFile.DateofBirth = request.DateofBirth;
                eweFile.EntryDate = request.EntryDate;
                eweFile.EarSignal = request.EarSignal   ;
                eweFile.BirthWeight = request.BirthWeight;
                eweFile.Note = request.Note;

                // 保存到数据库
                var result = await _eweRepository.UpdateAsync(eweFile);
                
                if (result>0)
                {
                    _logger.LogInformation($"成功更新母羊档案，ID: {request.EweId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "母羊档案更新成功", data = true };
                }
                else
                {
                    _logger.LogError($"更新母羊档案失败，ID: {request.EweId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "母羊档案更新失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新母羊档案时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}